/** 
  *@CopyRight(c)2009 company Co.Ltd. 
  *@All right reserved.
  *@module name: App.Base.SystemManage.SystemRolesManage
  *@description:
  *
  *@author: lugj
  *@version: 1.0
  *@date: 2009/06/25
  *@last date: 2009/07/15
  *@history:
    1.
    2.
  *@bugs:
    1. 
    2. 
  *
*/ 

Ext.namespace("App.Base.SystemManage");

//SystemRolesManage Class
App.Base.SystemManage.SystemRolesManage = function(config){
	this.config = config;
	this.MODULE_ID = App.Base.Common.func.generateGlobalUniqueId(this.config, 'SYSROLESMGR');

	this.OpCmd = App.Base.common.param.OP_CMD_NONE;
	this.QueryCmd = App.Base.common.param.OP_CMD_QUERY;

	this.waitOpLoadMask = new Ext.LoadMask(Ext.getBody(), {msg: "系统正在处理客户端请求，请稍候...", removeMask: false});
	this.waitOpLoadMask.show();

	//
	this.handlerReqSuccess = function(response){
		this.waitOpLoadMask.hide();
		//var result = decodeURIComponent(response.responseText);
		var result = Ext.decode(response.responseText);
		//{returnCode: , msg: );
		
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			//msg: result.returnCode + '：'+ result.msg,
			msg: result.msg,
			icon: (result.returnCode == App.Base.common.param.REQ_SUCCESS) ? Ext.MessageBox.INFO:Ext.MessageBox.ERROR
		});
		
		if (result.returnCode == App.Base.common.param.REQ_SUCCESS)
		{
			if (this.OpCmd == App.Base.common.param.OP_CMD_ADD)
			{
				this.tree.getNodeById(this.savedRoleParentId).reload();
			}
			else if (this.OpCmd == App.Base.common.param.OP_CMD_MODIFY)
			{
				this.tree.getNodeById(this.savedRoleId).remove();
				this.tree.getNodeById(this.savedRoleParentId).reload();
			}
			else if (this.OpCmd == App.Base.common.param.OP_CMD_DELETE)
			{
				if (this.savedRoleId == null)
				{
					this.asyncTreeNode.reload();
				}
				else
				{
					this.tree.getNodeById(this.savedRoleId).remove();
				}
			}
		}
		//
		this.OpCmd = App.Base.common.param.OP_CMD_NONE;
		this.store.load({params:{start:0, limit: Ext.getCmp('pagingtbl' + this.MODULE_ID).pageSize}});
	};

	this.handlerReqFailure = function(){
		this.waitOpLoadMask.hide();
		App.Base.Common.func.MESSAGEBOX_SHOW({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '服务器请求操作失败，请稍候重试',
			icon: Ext.MessageBox.ERROR
		});	
	};

	this.doRequest = function(config){
		if (config.params != null)
		{
			this.waitOpLoadMask.show();
			
			App.Base.Common.func.request({
				method: 'POST',
				url: App.Base.common.param.SYSROLESMGR_OPERATION_DATAURL,
				success: this.handlerReqSuccess,
				failure: this.handlerReqFailure,
				scope: this,
				params: config.params
			});
		}	
	};

	this.handler = function(o){
		if (o.action == App.Base.common.param.BUTTON_ACTION_NONE)
		{
			return;
		}
		var roleId = '';
		var roleName = Ext.getCmp('roleName' + o.MODULE_ID).getValue();
		var roleParentId = Ext.getCmp('roleParentId' + o.MODULE_ID).getValue();
		var roleDesc = Ext.getCmp('roleDesc' + o.MODULE_ID).getValue();
		var normalImgUrl = Ext.getCmp('normalImgUrl' + o.MODULE_ID).getValue();
		var leafNodeFlag = Ext.getCmp('leafNodeFlag' + o.MODULE_ID).getValue() == true ? '0' : '1';
		var expandImgUrl = Ext.getCmp('expandImgUrl' + o.MODULE_ID).getValue();
		var displayRankingIndex = Ext.getCmp('displayRankingIndex' + o.MODULE_ID).getValue();
		var sysHoldFlag = Ext.getCmp('sysHoldFlag' + o.MODULE_ID).getValue();
		var state = Ext.getCmp('state' + o.MODULE_ID).getValue();

		if (this.OpCmd == App.Base.common.param.OP_CMD_MODIFY)
		{
			roleId = o.config.initValues.id;

			if (roleId == roleParentId)
			{
				App.Base.Common.func.MESSAGEBOX_SHOW({
					title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
					msg: '角色类型设置错误',
					icon: Ext.MessageBox.ERROR
				});		
				this.OpCmd = App.Base.common.param.OP_CMD_NONE;
				return;
			}
			this.savedRoleId = roleId + this.MODULE_ID; 
		}
		this.savedRoleParentId = roleParentId + this.MODULE_ID; 

		var params = 'SYS_OP_CMD=' + encodeURIComponent(this.OpCmd) 
			+ '&ROLE_XTYPE_ID=' + encodeURIComponent(roleId)
			+ '&ROLE_XTYPE_PARENT_ID=' + encodeURIComponent(roleParentId)
			+ '&ROLE_XTYPE_NAME=' + encodeURIComponent(roleName)
			+ '&ROLE_XTYPE_DESC=' + encodeURIComponent(roleDesc)
			+ '&NORMAL_IMG_URL=' + encodeURIComponent(normalImgUrl)
			+ '&EXPAND_IMG_URL=' + encodeURIComponent(expandImgUrl)
			+ '&LEAF_NODE_FLAG=' + encodeURIComponent(leafNodeFlag)
			+ '&DISPLAY_RANKING_INDEX=' + encodeURIComponent(displayRankingIndex)
			+ '&SYS_HOLD_FLAG=' + encodeURIComponent(sysHoldFlag)
			+ '&STATE=' + encodeURIComponent(state);
		this.doRequest({params: params});
	};

	this.addRole = function(node){
		this.OpCmd = App.Base.common.param.OP_CMD_ADD;
		new App.Base.SystemManage.SystemRolesMgrWindow({
			id: this.MODULE_ID,
			title: '新增角色(类型)',
			iconCls: 'x-menu-personinfolist-add',
			OpCmd: this.OpCmd,
			initValues: {
				id: node.id.substr(0, node.id.length - this.MODULE_ID.length),
				text: node.text
			},
			handler: this.handler,
			scope: this
		}).getMainPanel().show();
	};

	this.modifyRole = function(node){
		if (node.text.trim() == this.asyncTreeNode.text.trim())
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '系统不允许修改树根节点',
				icon: Ext.MessageBox.ERROR
			});
			return;
		}
		this.OpCmd = App.Base.common.param.OP_CMD_MODIFY;
		new App.Base.SystemManage.SystemRolesMgrWindow({
			id: this.MODULE_ID,
			title: '修改角色(类型)',
			iconCls: 'x-menu-systemmenusmanage-modify',
			OpCmd: this.OpCmd,
			initValues: {
				id: node.id.substr(0, node.id.length - this.MODULE_ID.length),
				text: node.text,
				parentId: node.parentNode.id.substr(0, node.parentNode.id.length - this.MODULE_ID.length),
				parentText: node.parentNode.text,
				roleDesc: node.attributes['qtip'],
				icon: node.attributes['icon'],
				leafNodeFlag: node.attributes['leaf'],
				expandIcon: node.attributes['expandIcon'],
				displayRankingIndex: node.attributes['displayRankingIndex'],
				sysHoldFlag: node.attributes['sysHoldFlag'],
				state: node.attributes['state']
			},
			handler: this.handler,
			scope: this
		}).getMainPanel().show();
	};

	this.deleteSingleRole = function(node){
		if (node.text.trim() == this.asyncTreeNode.text.trim())
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '系统不允许删除树根节点',
				icon: Ext.MessageBox.ERROR
			});
			return;
		}

		if (node.hasChildNodes())
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '系统不允许删除子节点不为空的节点',
				icon: Ext.MessageBox.ERROR
			});
			return;
		}

		Ext.MessageBox.show({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '确定要删除角色(类型) [' + node.text + ']',
			buttons: Ext.MessageBox.YESNO,
			icon: Ext.MessageBox.QUESTION,
			fn: function(btn){
				if (btn == 'yes')
				{
					this.savedRoleId = node.id;
					this.doDelete(node.id.substr(0, node.id.length - this.MODULE_ID.length));
				}
			},
			scope: this
		});	
	};

	this.deleteMultiRoles = function(){
		if(!this.grid.selModel.hasSelection()) 
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '请选择删除的角色',
				icon: Ext.MessageBox.ERROR
			});					
			return;
		}

		var roleIds = "";
		var records = this.grid.getSelectionModel().getSelections();
		var length = records.length;
		for (var count = 0; count < length; count++)
		{
			roleIds += records[count].get("roleId");
			if (count < length - 1)
			{
				roleIds += App.Base.common.param.SPLIT_CHARS_VERTICAL_LINE;
			}
		}

		Ext.MessageBox.show({
			title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
			msg: '确定要删除选定的角色',
			buttons: Ext.MessageBox.YESNO,
			icon: Ext.MessageBox.QUESTION,
			fn: function(btn){
				if (btn == 'yes')
				{
					this.savedRoleId = null;
					this.doDelete(roleIds);
				}
			},
			scope: this
		});		
	};

	this.doDelete = function(ids){
		this.OpCmd = App.Base.common.param.OP_CMD_DELETE;
		var params = 'SYS_OP_CMD=' + encodeURIComponent(this.OpCmd) 
			+ '&ROLE_XTYPE_ID=' + encodeURIComponent(ids);
		
		this.doRequest({params: params});
	};

	this.doQuery = function(){
		if (this.QueryCmd == App.Base.common.param.OP_CMD_QUERY)
		{
			if (this.firstTreeNodeLoading === true)
			{
				this.firstTreeNodeLoading = false;
				this.node = '';
				this.roleName = '';
			}
		}

		this.store.load({params:{start:0, limit: Ext.getCmp('pagingtbl' + this.MODULE_ID).pageSize}});
	};

	this.doSearch = function(){
		this.QueryCmd = App.Base.common.param.OP_CMD_QUERY;
		this.roleName = Ext.getCmp('txtRoleName' + this.MODULE_ID).getValue();
		this.doQuery();
	};

	//
	this.asyncTreeNode = new Ext.tree.AsyncTreeNode({
		id: App.Base.common.param.SYSROLESMGR_TREE_ROOTNODE_ID + this.MODULE_ID,
		text: App.Base.common.param.SYSROLESMGR_TREE_ROOTNODE_NORMAL_TITLE,
		singleClickExpand: true,
		icon: App.Base.common.param.SYSROLESMGR_TREE_ROOTNODE_NORMALICON_URL,
		expandIcon: App.Base.common.param.SYSROLESMGR_TREE_ROOTNODE_EXPANDICON_URL,
		qtip: App.Base.common.param.SYSROLESMGR_TREE_ROOTNODE_QTIP
	});
	
    this.treeCtxmenu = new Ext.menu.Menu({
		items: [{
			id: 'treeCtxmenuDetails' + this.MODULE_ID,
			text: '查看角色子类',
			iconCls: 'x-menu-systemmanage-checkdetails'
		},'-',{
			id: 'treeCtxtmenuAdd' + this.MODULE_ID,
			text: '新增角色子类',
			iconCls: 'x-menu-systemmanage-roleadd'
		},{
			id: 'treeCtxtmenuModify' + this.MODULE_ID,
			text: '修改角色类型',
			iconCls: 'x-menu-systemmanage-rolemodify'
		},{
			id: 'treeCtxtmenuDelete' + this.MODULE_ID,
			text: '删除角色类型',
			iconCls: 'x-menu-systemmanage-roledelete'
		},'-',{
			id: 'treeCtxtmenuReload' + this.MODULE_ID,
			text: '重载节点',
			iconCls: 'x-menu-mainframe-refresh'
		}],
		listeners: {
			click: function(menu, menuItem, e){
				this.treeCtxmenu.hide();
			   
				var menuItemId = menuItem.getId();
				var node = this.tree.getSelectionModel().getSelectedNode();
				
				if (node == null)
				{
					return;
				}

				switch(menuItemId)
				{
					case 'treeCtxmenuDetails' + this.MODULE_ID:
						this.QueryCmd = App.Base.common.param.OP_CMD_NONE;
						this.node = node.id.substr(0, node.id.length - this.MODULE_ID.length);
						this.doQuery();
						break;
					case 'treeCtxtmenuAdd' + this.MODULE_ID:
						this.addRole(node);
						break;
					case 'treeCtxtmenuModify' + this.MODULE_ID:
						this.modifyRole(node);
						break;
					case 'treeCtxtmenuDelete' + this.MODULE_ID:
						this.deleteSingleRole(node);
						break;
					case 'treeCtxtmenuReload' + this.MODULE_ID:
						node.reload();
						break;
					default:
						break;
				}
					   
			}, 
			scope: this
		}
	});

	this.tree = new Ext.tree.TreePanel({
		id: 'tree' + this.MODULE_ID,
		border: false,
		autoScroll: true,
		root: this.asyncTreeNode,
		loader: new Ext.tree.TreeLoader({
			dataUrl: App.Base.common.param.SYSROLESMGR_ASYNC_TREELOADER_DATAURL,
			baseParams: {
				module: encodeURIComponent(this.MODULE_ID),
				leaf: encodeURIComponent('2') //leaf: 0查询非叶节点 1查询叶节点 2查询所有
			}
		}),
		listeners: {
			load: function(node){
				this.waitOpLoadMask.hide();
				if (typeof(this.firstTreeNodeLoading) == "undefined")
				{
					this.firstTreeNodeLoading = true;
					this.doQuery()
				}
			},			
			dblclick: function(node, e){
				if (node.isLeaf())
				{
					this.modifyRole(node);
				}
			},
			beforeexpandnode: function(node){
				node.select();
				node.setIcon(node.attributes['expandIcon']);				
			},
			beforecollapsenode: function(node){
				node.select();
				node.setIcon(node.attributes['icon']);				
			},
			contextmenu: function(node, e){
				e.preventDefault();
				node.select();
				if (node.isLeaf())
				{
					Ext.getCmp('treeCtxmenuDetails' + this.MODULE_ID).disable();
					Ext.getCmp('treeCtxtmenuAdd' + this.MODULE_ID).disable();
					Ext.getCmp('treeCtxtmenuReload' + this.MODULE_ID).disable();
				}
				else
				{
					Ext.getCmp('treeCtxmenuDetails' + this.MODULE_ID).enable();
					Ext.getCmp('treeCtxtmenuAdd' + this.MODULE_ID).enable();
					Ext.getCmp('treeCtxtmenuReload' + this.MODULE_ID).enable();
				}
				this.treeCtxmenu.showAt(e.getXY());
			},
			scope: this
		}
	});

    this.store = new Ext.data.Store({
		id: 'store' + this.MODULE_ID,
        proxy: new Ext.data.HttpProxy({url: App.Base.common.param.SYSROLESMGR_GRID_DATAURL}),
        reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
        }, [
            {name: 'roleId'},
            {name: 'roleName'},
            {name: 'roleDesc'},
            {name: 'roleParentName'},
            {name: 'sysHoldFlag'},
            {name: 'state'}
        ]),
		listeners: {
			beforeload: function(store, options){
				options.params.queryCmd = encodeURIComponent(this.QueryCmd);
				options.params.roleName = encodeURIComponent(this.roleName);
				options.params.node = encodeURIComponent(this.node);
			},
			scope: this
		}
    });

	this.sm = new Ext.grid.CheckboxSelectionModel();//{handleMouseDown: Ext.emptyFn}

	this.grid = new Ext.grid.GridPanel({
		id: 'grid' + this.MODULE_ID,
    	border: false,
		autoScroll: true,
        stripeRows: true,
        loadMask: {msg: '系统正在加载角色数据，请稍候...'},
        //autoExpandColumn: 'roleName' + this.MODULE_ID,
        enableColumnMove: false,
		sm: this.sm,
        cm: new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(),
			{id: 'roleId' + this.MODULE_ID, header: '编码', dataIndex: 'roleId', hidden: true},
			{id: 'roleName' + this.MODULE_ID, header: '角色名称', dataIndex: 'roleName' , width: 168},
			{header: '角色描述', dataIndex: 'roleDesc' , width: 178},
			{header: '角色类型', dataIndex: 'roleParentName' , width: 168},
			{header: '系统创建', dataIndex: 'sysHoldFlag' , width: 64, align: 'center', renderer: function(value){
					if (value == '1')
					{
						return "是";
					}
					else if (value == '0')
					{
						return "否";
					}
					else
					{
						return "未知";
					}
			}},
			{header: '状态', dataIndex: 'state', width: 42, align: 'center', renderer: function(value){
					if (value == '0')
					{
						return "<font color='black'>正常</font>";
					}
					else if (value == '1')
					{
						return "<font color='green'>已冻结</font>";
					}
					else
					{
						return "<font color='green'>未知</font>";
					}
			}},
			this.sm
        ]),

        store: this.store,

		tbar: new Ext.Toolbar({
			id: 'tbar02' + this.MODULE_ID,
			border: false,

			items : ['-', 
				new Ext.form.TextField({
					id: 'txtRoleName' + this.MODULE_ID,
					emptyText: '请输入搜索的角色名称...',
					width: 220,
					enableKeyEvents: true,
					listeners: {
						keydown: function(o, e){
							if (e.getCharCode() == 13)
							{
								this.doSearch();
							}
						},
						scope: this
					}			
			}),
				new Ext.Button({
					id: 'btnSearch' + this.MODULE_ID,
					text: '<font color="#0000E3">搜索</font>',
					iconCls: 'x-button-systemmanage-search',
					handler: function(){
						this.doSearch();
					},
					scope: this
			}), '-',
				new Ext.Button({
					id: 'btnReset' + this.MODULE_ID,
					text: '<font color="#0000E3">重置</font>',
					iconCls: 'x-menu-systemmenusmanage-rset',
					handler: function(){
						Ext.getCmp('txtRoleName' + this.MODULE_ID).setValue('');
					},
					scope: this
			}), '-', '->', '-', {
				text:'<font color="blue">批量删除</font>',
				iconCls: 'x-menu-systemmanage-brick_delete',
				handler: function(){
					this.deleteMultiRoles();
				},
				scope: this
			}, '-']
		}),
		
		bbar: new Ext.PagingToolbar({
			id: 'pagingtbl' + this.MODULE_ID,
            pageSize: App.Base.common.param.GRID_PAGE_SIZE_15,
            store: this.store,
            displayInfo: true,
            displayMsg: '共 {2} 条',//'显示第 {0} 条到 {1} 条记录，共 {2} 条',
            emptyMsg: "没有记录",
            plugins: new Ext.ux.PageSizePlugin()
        }),
        viewConfig: {
            //forceFit: true,
            enableRowBody: true,
            getRowClass: function(record, rowIndex, p, ds) {
                var cls = 'white-row';
                switch (rowIndex%2) {
                    case 1:
                        cls = 'red-row'
                        break;
                }
                return cls;
            }
        }
    });

	this.formPanel = new Ext.FormPanel({
		id: 'formPanel' + this.MODULE_ID,
		border: false,
		autoScroll: true,
		tbar: new Ext.Toolbar({
			border: false,
			items : ['-', '->', '-']
		}),
		layout: 'border',
		items: [{
			region: 'west',
			title: '角色类型',
			width : 280,
			minWidth: 220,
			border: true,
			autoScroll: true,
			split : true,
			collapsible : true,

			tbar: new Ext.Toolbar({
				border: false,
				items : ['-', {
					text:'<font color="blue">新增</font>',
					iconCls: 'x-menu-systemmanage-roleadd',
					handler: function(){
						this.addRole({
							id: App.Base.common.param.SYSROLESMGR_TREE_ROOTNODE_ID + this.MODULE_ID,
							text: App.Base.common.param.SYSROLESMGR_TREE_ROOTNODE_NORMAL_TITLE
						});
					},
					scope: this
				}, '-', {
					text:'<font color="blue">修改</font>',
					iconCls: 'x-menu-systemmanage-rolemodify',
					handler: function(){
						var node = this.tree.getSelectionModel().getSelectedNode();
						if (node == null)
						{
							App.Base.Common.func.MESSAGEBOX_SHOW({
								title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
								msg: '请选择修改的角色类型',
								icon: Ext.MessageBox.ERROR
							});	
							return;
						}
						this.modifyRole(node);
					},
					scope: this
				}, '-', {
					text:'<font color="blue">删除</font>',
					iconCls: 'x-menu-systemmanage-roledelete',
					handler: function(){
						var node = this.tree.getSelectionModel().getSelectedNode();
						if (node == null)
						{
							App.Base.Common.func.MESSAGEBOX_SHOW({
								title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
								msg: '请选择删除的角色类型',
								icon: Ext.MessageBox.ERROR
							});	
							return;
						}
						this.deleteSingleRole(node);
					},
					scope: this
				}, '-'
				]
			}),

			layout: 'fit',
			items: [this.tree]
		}, {
			region: 'center',
			title: '角色',
			minWidth: 420,
			border: true,
			autoScroll: true,
			layout: 'fit',
			items: [this.grid]
		}]
	});

	this.asyncTreeNode.expand();

	//this.formPanel.doLayout();

	//defined methods.
    if((typeof App.Base.SystemManage.SystemRolesManage.SIMULATE_SHARED_METHODS_FLAG) == "undefined")
    {
        App.Base.SystemManage.SystemRolesManage.SIMULATE_SHARED_METHODS_FLAG = true;   

        App.Base.SystemManage.SystemRolesManage.prototype.getMainPanel = function(){   
            return this.formPanel;  
        };
 
        //simulating the class's constructor().
        var __ctor = function(){
        }();
    }
}